package array.leetcode.medium;

/**
 * @author bruin_du
 * @description 排序数组中只出现一次的数字
 * @date 2022/8/27 23:50
 **/
public class OfferII070_ingleNonDuplicate {
    public int singleNonDuplicate(int[] nums) {
        int n = nums.length;
        if (n == 1) return nums[0];
        int left = 0, right = n - 1;
        while (left < right) {
            int mid = left + (right - left >> 1);
            // 记录mid左右两边的元素个数
            // 后面根据区间元素是奇偶判断该数在哪个区间
            int m1 = mid - left, m2 = right - mid;
            if (mid > 0 && nums[mid - 1] == nums[mid]) {
                if (--m1 % 2 == 0) {
                    left = mid + 1;
                } else {
                    right = mid - 2;
                }
            } else if (mid < n - 1 && nums[mid] == nums[mid + 1]){
                if (--m2 % 2 == 0) {
                    right = mid - 1;
                } else {
                    left = mid + 2;
                }
            } else {
                // 此时mid就是这个数
                left = mid;
                break;
            }
        }
        return nums[left];
    }
}
